const Router = require('koa-router')
const { catchError, generateOk, check } = require('../../lib/check')
const { searchAccount } = require("../../model/accounts")
const tencentcloud = require("tencentcloud-sdk-nodejs");
const { setCode, searchCode, deleteCode, editCode } = require('../../model/confirmCode')

const code = new Router()

code.post('/send', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!(data.account), "Param_Lost")
    const time = (new Date()).getTime()
    const findCode = searchCode(data.account)
    const code = getRandomSixNum()
    sendCode(data.account, code)
    if (!!findCode) {
      editCode({ ...findCode, code: code, time: time })
    } else {
      setCode({ account: data.account, code: code, time: time })
    }
    ctx.body = generateOk({})
  } catch (e) {
    catchError(e, ctx)
  }
})

function getRandomSixNum() {
  let RandomSixStr = ''
  for (let i = 0; i < 6; i++) {
    RandomSixStr += String(Math.floor(Math.random() * 10))
  }
  return RandomSixStr
}

function sendCode(number, code) {

  const SmsClient = tencentcloud.sms.v20210111.Client;

  const clientConfig = {
    credential: {
      secretId: "AKIDUnsiIdkcFRTGg0FJ9nDQO8ew0qRoxsZ1",
      secretKey: "JOFrFQM3WjhPt76qLceT4TfdNuGOIyQe",
    },
    region: "ap-nanjing",
    profile: {
      signMethod: "HmacSHA256",
      httpProfile: {
        reqMethod: "POST",
        reqTimeout: 30,
        endpoint: "sms.tencentcloudapi.com",
      },
    },
  };

  const client = new SmsClient(clientConfig);
  const params = {
    PhoneNumberSet: [
      "+86" + number
    ],
    SignName: "喜悲的天地",
    SmsSdkAppId: "1400668671",
    TemplateId: "1405526",
    TemplateParamSet: [code]
  };
  client.SendSms(params, function (err, response) {
    // 请求异常返回，打印异常信息
    if (err) {
      console.log(err)
      return
    }
    // 请求正常返回，打印response对象
    check(response.SendStatusSet[0].Code === 'Ok', 'Fail_Send')
    console.log(response)
  })
}

code.post('/check', async (ctx) => {
  try {
    const data = ctx.request.body
    check(!!(data.account), "Params_Lost")
    check(!!(data.code), "Params_Lost")
    const findCode = searchCode(data.account)
    if (!!findCode) {
      if (data.code === findCode.code) {
        const time = (new Date()).getTime()
        if (time - findCode.time >= 180000) {
          deleteCode(data.account)
          check(false, 'Code_Out_Date')
        } else {
          deleteCode(data.account)
          ctx.body = generateOk()
        }
      } else {
        check(false, "Wrong_Code")
      }
    } else {
      check(false, "Wrong_Code")
    }

  } catch (e) {
    catchError(e, ctx)
  }
})

module.exports = code